package com.statistics.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.common.utils.PageUtils;
import com.common.utils.poi.ExcelUtil;
import com.statistics.domain.bo.UnitAchievementBo;
import com.statistics.domain.vo.HxProjectNumVo;
import com.statistics.domain.vo.UnitAchievementVo;
import com.statistics.domain.vo.UnitPersonVo;
import com.statistics.domain.vo.ZxProjectNumVo;
import com.statistics.mapper.FixedReportMapper;
import com.statistics.service.FixedReportService;
import com.statistics.util.AchExportUtils;
import com.statistics.util.HonorExportUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.*;


/**
 * FixedReportServiceImpl
 *
 * @author chenyy
 * &#064;date 2025/2/25 12:20
 */
@Service
public class FixedReportServiceImpl implements FixedReportService {

    @Resource
    private FixedReportMapper fixedReportMapper;

    @Override
    public JSONObject getUnitAchievement(Integer beginYear, Integer endYear, int type) {
        List<UnitAchievementBo> bos = new ArrayList<>();
        for (int year = beginYear; year <= endYear; year++) {
            if (type == 1) {
                // 每次循环重新设置分页参数
                PageUtils.startPage();
            }
            bos.addAll(fixedReportMapper.getUnitAchievement(year));
        }
        // 按单位名称聚合数据
        Map<String, UnitAchievementVo> voMap = new LinkedHashMap<>();

        for (UnitAchievementBo bo : bos) {
            String unitId = bo.getUnitId();
            UnitAchievementVo vo = voMap.computeIfAbsent(unitId, k -> {
                UnitAchievementVo newVo = new UnitAchievementVo();
                newVo.setUnitId(unitId);
                newVo.setUnitName(bo.getUnitName());
                // 初始化所有Map字段
                newVo.setPaper(new HashMap<>());
                newVo.setBook(new HashMap<>());
                newVo.setResearchReport(new HashMap<>());
                newVo.setAppraisalProduct(new HashMap<>());
                newVo.setArtProduct(new HashMap<>());
                newVo.setPatent(new HashMap<>());
                newVo.setCopyright(new HashMap<>());
                newVo.setStandard(new HashMap<>());
                newVo.setMedicine(new HashMap<>());
                newVo.setBreed(new HashMap<>());
                newVo.setMeeting(new HashMap<>());
                newVo.setLecture(new HashMap<>());
                newVo.setJoinMeeting(new HashMap<>());
                newVo.setPersonnelDispatch(new HashMap<>());
                newVo.setPersonnelAccept(new HashMap<>());
                return newVo;
            });

            int year = bo.getYear();

            // 更新各字段的Map
            safePut(vo.getPaper(), year, bo.getPaper());
            safePut(vo.getBook(), year, bo.getBook());
            safePut(vo.getResearchReport(), year, bo.getResearchReport());
            safePut(vo.getAppraisalProduct(), year, bo.getAppraisalProduct());
            safePut(vo.getArtProduct(), year, bo.getArtProduct());
            safePut(vo.getPatent(), year, bo.getPatent());
            safePut(vo.getCopyright(), year, bo.getCopyright());
            safePut(vo.getStandard(), year, bo.getStandard());
            safePut(vo.getMedicine(), year, bo.getMedicine());
            safePut(vo.getBreed(), year, bo.getBreed());
            safePut(vo.getMeeting(), year, bo.getMeeting());
            safePut(vo.getLecture(), year, bo.getLecture());
            safePut(vo.getJoinMeeting(), year, bo.getJoinMeeting());
            safePut(vo.getPersonnelDispatch(), year, bo.getPersonnelDispatch());
            safePut(vo.getPersonnelAccept(), year, bo.getPersonnelAccept());
        }

        JSONObject json = new JSONObject();
        json.put("data", voMap.values());
        json.put("total", fixedReportMapper.getUnitNum());
        return json;
    }

    // 安全写入Map
    private void safePut(Map<String, Integer> map, int year, Integer value) {
        if (value == null) return;
        map.put(String.valueOf(year), value);
    }

    @Override
    public List<Map<String, Object>> getUnitHonor(Integer beginYear, Integer endYear) {
        List<Integer> years = new ArrayList<>();
        for (int year = beginYear; year <= endYear; year++) {
            years.add(year);
        }
        return fixedReportMapper.getUnitHonor(years);
    }

    @Override
    public List<UnitPersonVo> getUnitPersonType() {
        return fixedReportMapper.getUnitPersonType();
    }

    @Override
    public List<HxProjectNumVo> getHxProjectNum(Integer beginYear, Integer endYear) {
        return fixedReportMapper.getHxProjectNum(beginYear, endYear);
    }

    @Override
    public List<ZxProjectNumVo> getZxProjectNum(Integer beginYear, Integer endYear) {
        return fixedReportMapper.getZxProjectNum(beginYear, endYear);
    }

    @Override
    public void getUnitAchievementExport(Integer beginYear, Integer endYear, HttpServletResponse response) throws Exception {
        JSONArray data = getUnitAchievement(beginYear, endYear, 2).getJSONArray("data");
        AchExportUtils.exportExcel(response, data, "各单位成果统计表");
    }

    @Override
    public void getUnitHonorExport(Integer beginYear, Integer endYear, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> unitHonor = this.getUnitHonor(beginYear, endYear);
        HonorExportUtils.exportExcel(response, unitHonor, "各单位获奖情况统计表");
    }

    @Override
    public void getUnitPersonTypeExport(HttpServletResponse response) {
        String[] unitPersonVo = Arrays.stream(UnitPersonVo.class.getDeclaredFields()).map(Field::getName).toArray(String[]::new);
        // 各单位科研人员职称_学历_学位分析表
        List<UnitPersonVo> personVos = getUnitPersonType();
        ExcelUtil<UnitPersonVo> personVoExcelUtil = new ExcelUtil<>(UnitPersonVo.class);
        personVoExcelUtil.showColumn(unitPersonVo);
        personVoExcelUtil.exportExcel(response, personVos, "各单位科研人员职称_学历_学位分析表");
    }

    @Override
    public void getHxProjectNumExport(Integer beginYear, Integer endYear, HttpServletResponse response) {
        String[] hxProjectNumVo = Arrays.stream(HxProjectNumVo.class.getDeclaredFields()).map(Field::getName).toArray(String[]::new);
        // 各单位科研人员职称_学历_学位分析表
        List<HxProjectNumVo> hxProjectNum = fixedReportMapper.getHxProjectNum(beginYear, endYear);
        ExcelUtil<HxProjectNumVo> hxExcelUtil = new ExcelUtil<>(HxProjectNumVo.class);
        hxExcelUtil.showColumn(hxProjectNumVo);
        hxExcelUtil.exportExcel(response, hxProjectNum, "横向项目各年份项目数量统计表");
    }

    @Override
    public void getZxProjectNumExport(Integer beginYear, Integer endYear, HttpServletResponse response) {
        String[] zxProjectNumVo = Arrays.stream(ZxProjectNumVo.class.getDeclaredFields()).map(Field::getName).toArray(String[]::new);
        // 各单位科研人员职称_学历_学位分析表
        List<ZxProjectNumVo> zxProjectNum = fixedReportMapper.getZxProjectNum(beginYear, endYear);
        ExcelUtil<ZxProjectNumVo> zxExcelUtil = new ExcelUtil<>(ZxProjectNumVo.class);
        zxExcelUtil.showColumn(zxProjectNumVo);
        zxExcelUtil.exportExcel(response, zxProjectNum, "纵向项目各年份项目数量统计表");
    }
}